import { useState,useEffect } from 'react';
import './App.css'; 

function Todo({todo,toggleTodoState,removeTodo,index}) {
  return (
    <div className="listItem">
      <div className='text todo' style={{textDecoration: todo.completed?"line-through":"" }} onClick={()=>toggleTodoState(index) } >{todo.title}</div>
        <div className='subTitle'>
          <div className='todo' style={{textDecoration: todo.completed?"line-through":"" }}
    onClick={()=>toggleTodoState(index) } >{todo.creatAt}</div>
     
          <button onClick={()=>removeTodo(index)}>X</button>
        </div>
    </div>
  )
}
function FormInput({inputCb}) {
  const [text,setText] = useState("");
  const submitHandle = (e)=>{
    e.preventDefault();
    if(!text) return;
    inputCb(text);
    setText("")
  }
  return (
    <form onSubmit={(e)=>submitHandle(e)}>
    <input type="text" className='inputer'  placeholder='输入一条计划吧，不管能不能干完' value={text} onChange={(v)=>{setText(v.target.value)}} />
  </form>
  )
}
function App() {
  const [todos,setTodos]=useState([])
  
  useEffect(()=>{
   setTodos(readTodos());
  },[])

  function readTodos(){
    const tempTodos=localStorage.getItem("todos");
    return tempTodos?JSON.parse(tempTodos):[]
  }
  function addTodo(text) {
    const newTodo={id:todos.length+1,title:text,creatAt:new Date().toLocaleTimeString(),completed:false}
     const newTodos = [...todos,newTodo]
     setTodos(newTodos);
     localStorage.setItem("todos",JSON.stringify(newTodos))
  }
  function removeTodo(index){
    const newTodos = [...todos];
    newTodos.splice(index,1);
    setTodos(newTodos);
    localStorage.setItem("todos",JSON.stringify(newTodos))
  }
  function toggleTodoState(index) {
    const newTodos = [...todos];
    newTodos[index].completed = !newTodos[index].completed
    setTodos(newTodos); 
    localStorage.setItem("todos",JSON.stringify(newTodos))
  }
  return (
    <div className='content'>
      <div className='title'>Todo List</div>
      <div className='card'>
      {
        todos.map((x,index)=>(
          <Todo key={x.id} todo={x} index={index} toggleTodoState={toggleTodoState} removeTodo={removeTodo}/>
          ))
        } 
      </div>
      <div className='inputer-wrapper'>
       <FormInput inputCb = {addTodo}/>
      </div>
    </div>
  );
}

export default App;
